import React, { useContext, useState, useEffect, useMemo } from 'react';
import { Table, Form, Button, message } from 'antd';
import lodash from 'lodash';
import moment from 'moment';
import UpdateRemoveMaterialModal from './UpdateRemoveMaterialModal';
import { getNeedTableColumns } from '../mconfig/UpdateTableColumns';
import { NeedUpdateContext } from '../common/NeedContext';
import { IActionEnum } from '../common/NeedReducer';
import { UpdateNeedMaterialBatchUpload } from './UpdateNeedMaterialBatchUpload';
import { JZLZ_STATE, SHZ_STATE, XQBZ_STATE, ZRBGH_STATE } from '../common/Format';
import { BZZ_CHECKSTATE, FWL_SUPPLY, GCL_SUPPLY, HWL_SUPPLY, SHTH_CHECKSTATE } from '../../Acommon';
import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { NeedUpdateAPI } from '../common/type';
import SelectProjectModal from '../../Acomponents/SelectProjectModal/SelectProjectModal';

/**
 * @UpdateNeedMaterial 需求详情页物料列表组件
 * @param openDrawer 打开物料详情
 * @param openModal 打开物料选择弹窗
 * @param onSave 保存当前表格修改数据
 * @returns
 */
const UpdateNeedMaterial: React.FC<NeedUpdateAPI.IUpdateMaterial> = ({ openDrawer, openModal, onSave, openAddEngIneer, tableForm }) => {
  const { isView, prefixCls, needInfo, materialList, dispatch, nodesFlowListMemo, curRes } = useContext(NeedUpdateContext);

  // 所有物料的预估总价 - top
  const [totalNeedPrice, setTotalNeedPrice] = useState<Record<string, any>>({
    topPrice: 0,
    bottomPrice: 0,
    allPrice: 0,
  });
  // 是否展示资金来源弹窗
  const [isShowProject, setIsShowProject] = useState<Record<string, any>>({});
  // 表格数据
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);
  // 表格多选的key值保存
  const [tableKeys, setTableKeys] = useState<any[]>([]);
  // 批量上传弹窗开关
  const [batchModal, setBatchModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });

  // 删除物料二次确认弹窗所需信息
  const [removeMaterialInfo, setRemoveMaterialInfo] = useState<NeedUpdateAPI.IUpdateRemoveMaterialState>({
    id: 0,
    fullName: '',
    isShow: false,
  });

  // 设置需求表格内容,填充物料预估单价，数量，及计算单条物料总价
  useEffect(() => {
    if (Array.isArray(materialList)) {
      if (dataSource.length) {
        const tempData: Record<string, any>[] = [];
        // 当前物料的所有id
        const ids = dataSource.map((item) => item.materialIDS);
        // 选择物料后，若当前存在该物料，继续使用当前物料，否则新增
        materialList.forEach((materialItem) => {
          const index = ids.indexOf(materialItem.materialIDS);
          if (index == -1) {
            const param = materialItem;

            // TODO: 梁豪杰 物料里是否携带物料预估单价，携带的话无需处理
            if (!param['expectPrice']) param['expectPrice'] = '0.00';
            if (!param['expectNum']) param['expectNum'] = 1;

            if (typeof param['supplyWay'] == 'undefined') param['supplyWay'] = '';
            if (typeof param['supplyKind'] == 'undefined') param['supplyKind'] = '';

            // 计算单条物料预估总价
            if (!param['expectPrice']) {
              // 初始的时候 expectPrice = undefined
              param['expectSum'] = '0.00';
            } else {
              param['expectSum'] = (param['expectPrice'] * param['expectNum']).toFixed(2);
            }
            tempData.push(param);
          } else {
            tempData.push(dataSource[index]);
          }
        });
        setDataSource(tempData);
      } else {
        // 选择物料后，该物料没有单价以及数量，默认手动填充
        const tempData: Record<string, any>[] = materialList.map((item) => {
          const param = item;
          // TODO: 梁豪杰 物料里是否携带物料预估单价，携带的话无需处理
          if (!param['expectPrice']) param['expectPrice'] = '0.00';
          if (!param['expectNum']) param['expectNum'] = 1;

          if (typeof param['supplyWay'] == 'undefined') param['supplyWay'] = '';
          if (typeof param['supplyKind'] == 'undefined') param['supplyKind'] = '';

          // 计算单条物料预估总价
          if (!param['expectPrice']) {
            // 初始的时候 expectPrice = undefined
            param['expectSum'] = '0.00';
          } else {
            param['expectSum'] = (param['expectPrice'] * param['expectNum']).toFixed(2);
          }
          return param;
        });
        setDataSource(tempData);
      }
    }
  }, [materialList]);

  //
  // useEffect(() => {
  //   let tempData = materialList?.map((item) => {
  //     const param = item;

  //     // 计算单条物料预估总价 [初始的时候 expectPrice = undefined]
  //     if (!param['expectPrice']) {
  //       param['expectSum'] = '0.00';
  //     } else {
  //       param['expectSum'] = (param['expectPrice'] * param['expectNum']).toFixed(2);
  //     }
  //     return param;
  //   })
  //   setDataSource(tempData);
  // }, [materialList])

  // 数据有改动后重新计算预估总计，遍历单条物料总价并加和
  useEffect(() => {
    let topPrice = 0.0;
    let bottomPrice = 0.0;
    let allPrice = 0.0;
    if (!dataSource || !dataSource.length) {
      setTotalNeedPrice({
        topPrice: '0.00',
        bottomPrice: '0.00',
        allPrice: '0.00',
      });
    } else {
      dataSource.forEach((item) => {
        allPrice += Number(item.expectSum || 0);
        if (
          item?.supplyType == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000` || //货物
          item?.supplyType == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1003` || //材料
          item?.supplyType == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1004` //资产
        ) {
          topPrice += Number(item.expectSum || 0);
        } else {
          bottomPrice += Number(item.expectSum || 0);
        }
      });
      setTotalNeedPrice({
        topPrice: topPrice?.toFixed(2),
        bottomPrice: bottomPrice?.toFixed(2),
        allPrice: allPrice?.toFixed(2),
      });
    }
    const param = {
      totalNeedPrice: allPrice?.toFixed(2),
      list: dataSource,
    };

    // 将最新数据抛出，以便外部获取
    onSave(param);
  }, [dataSource]);

  /**
   * @deleteMaterialList  移除物料列表
   * @param id 物料id
   */
  const deleteMaterialList = (id: number) => {
    const originData = lodash.cloneDeep(dataSource);
    const currentData = originData.filter((item) => item.id != id);
    setDataSource(currentData);
    dispatch({
      type: IActionEnum.UPDATE_MATERIAL_LIST,
      payload: currentData,
    });
  };

  /**
   * @onEditTable 物料表格编辑事件
   * @param value 修改后的值
   * @param type 修改元素标签类型， 区分标签做不同的数据修改
   * @param key 表格key值
   * @param record 表格单条数据
   */
  const onEditTable = ({ value, type, key, record }: NeedUpdateAPI.IUpdateEditTableState) => {
    const index = dataSource.findIndex((item: Record<string, any>) => item.materialIDS == record.materialIDS);
    const currentData = lodash.cloneDeep(dataSource);

    if (type == 'switch') {
      /**改变switch的值*/
      currentData[index][key] = Number(value);
      /**如果是关闭switch那么将url清空*/
      if (key === 'needProofFlag') {
        //需求论证
        if (!value) {
          currentData[index]['needProofURL'] = null;
        }
      } else if (key === 'needImportFlag') {
        //进口
        if (!value) {
          currentData[index]['needImportURL'] = null;
        }
      } else if (key === 'needSingleFlag') {
        //单一来源
        if (!value) {
          currentData[index]['needSingleURL'] = null;
        }
      } else if (key === 'isPlatform') {
        // 是否平台
        currentData[index][key] = Number(value);
      }
    } else if (type == 'InputNumber') {
      // 修改表格数量。重新计算预告总价
      if (key == 'expectNum') {
        currentData[index].expectNum = value;
        currentData[index].expectSum = ((value as number) * record.expectPrice).toFixed(2);
      }
      // 修改表格预估单价。重新计算预告总价
      if (key == 'expectPrice') {
        currentData[index].expectPrice = value;
        currentData[index].expectSum = ((value as number) * record.expectNum).toFixed(2);
      }
    } else if (type == 'TimePicker') {
      currentData[index][key] = value ? moment(value as any).format('YYYY-MM-DD HH:mm:ss') : null;
    } else if (type == 'UploadFormCommon') {
      // 上传文件
      currentData[index][key] = value;
    } else if (type == 'Select') {
      currentData[index][key] = value;
    } else if (type == 'Input') {
      if (key == 'packCode') {
        // 标包号
        currentData[index][key] = value;
      }
    } else if (type == 'project') {
      currentData[index]['projectCode'] = value?.xmdm;
      currentData[index]['projectName'] = value?.xmmc;
      currentData[index]['projectSum'] = value?.ysje;
    }

    setDataSource(currentData);
    dispatch({
      type: IActionEnum.UPDATE_MATERIAL_LIST,
      payload: currentData,
    });
  };

  // 第一表格的底部总价
  const ToptableFooterRender = () => {
    return (
      <span className={`${prefixCls}-material-table-sum`}>
        预估总价：<strong>{isShowTable ? totalNeedPrice?.topPrice : totalNeedPrice?.allPrice}</strong> &nbsp;元
      </span>
    );
  };

  // 第二表格的底部总价
  const BottomTableFooterRender = () => {
    return (
      <span className={`${prefixCls}-material-table-sum`}>
        预估总价：<strong>{totalNeedPrice?.bottomPrice}</strong> &nbsp;元
      </span>
    );
  };

  // 点击资金来源输入框
  const onProjectChange = (record) => {
    setIsShowProject({ isShow: true, record });
  };

  // table表格的选择框是否显示
  const rowSelectionMemo = useMemo(() => {
    if (
      (needInfo?.state && needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo) ||
      (needInfo?.state && needInfo?.state == ZRBGH_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo)
    ) {
      return {
        type: 'checkbox',
        onChange: (val: any[]) => {
          setTableKeys(val);
        },
      };
    } else {
      return undefined;
    }
  }, [needInfo?.state, nodesFlowListMemo, needInfo?.checkState]);

  // 是否展示第二个表格
  const isShowTable = useMemo(() => {
    if (isView) return false;
    if (!needInfo?.state) return true;
    if (needInfo?.state && needInfo?.state == XQBZ_STATE() && !needInfo?.checkState) return true;
    if (needInfo?.state && needInfo?.state == SHZ_STATE() && needInfo?.checkState == SHTH_CHECKSTATE()) return true;
    // if (needInfo?.state && needInfo?.state == FGLDSH_STATE()) return true;
    else return false;
  }, [needInfo?.state, isView, needInfo?.checkState]);

  return (
    <div>
      {/* 
      <Form form={tableForm} className="material-form"></Form>
      {needInfo?.state && needInfo?.state == JZLZ_STATE() && nodesFlowListMemo && needInfo?.checkState == BZZ_CHECKSTATE() ? (
        <div style={{ margin: '0.5rem 0rem' }}>
          <Button
            type="primary"
            // icon={<CloudUploadOutlined />}
            onClick={() => {
              if (tableKeys?.length) {
                setBatchModal({
                  isShow: true,
                  resObj: tableKeys,
                });
              } else {
                message?.warning('请至少选择一个标的');
              }
            }}
          >
            批量上传
          </Button>
        </div>
      ) : null} */}

      {/* 第一部分 货物类 */}
      <div className={isShowTable ? `${prefixCls}-material-table` : `${prefixCls}-material-tableHeight`}>
        {isShowTable && <div className={`${prefixCls}-material-tableTitle`}>一、货物清单</div>}
        <div className="list-table">
          <Table
            dataSource={isShowTable ? dataSource?.filter((item) => item?.supplyType == HWL_SUPPLY()) : dataSource}
            scroll={{ x: 'true', y: 'true' }}
            rowSelection={rowSelectionMemo as any}
            pagination={false}
            size={'small'}
            columns={getNeedTableColumns({
              needInfo,
              tableForm,
              nodesFlowListMemo,
              isView,
              curRes,
              onEditTable,
              setIsShowDetail: (id: string) => openDrawer({ id: id, isShow: true }),
              openMateridal: () => openModal(true),
              onRemove: (record: Record<string, any>) => setRemoveMaterialInfo({ id: record.id, fullName: record.fullName, isShow: true }),
              onProjectChange,
            })}
            bordered
            rowKey={'materialIDS'}
            footer={() => ToptableFooterRender()}
          />
        </div>

        {/* 删除物料二次确认弹窗 */}
        {removeMaterialInfo.isShow && (
          <UpdateRemoveMaterialModal
            info={removeMaterialInfo}
            onSubmit={() => {
              deleteMaterialList(removeMaterialInfo.id);
            }}
            onClose={() => {
              setRemoveMaterialInfo({
                id: 0,
                fullName: '',
                isShow: false,
              });
            }}
          />
        )}

        {/* 批量上传弹窗 */}
        {batchModal?.isShow && (
          <UpdateNeedMaterialBatchUpload
            status={batchModal}
            onClose={() => {
              setBatchModal({
                isShow: false,
                resObj: null,
              });
            }}
            onSave={(resObj) => {
              /** 遍历数据,判断如果选择了是，那么url是否上传，没有上传则需要提示！ */
              const newarr = dataSource?.map((item) => {
                const newObj = { ...item };
                if (tableKeys?.indexOf(item?.id) != -1) {
                  // 判断有没有需求论证意见url返回 && 当预估总价大于50w的时候才允许上传需求论证意见
                  if (resObj?.['needProofURL'] && !(Number(newObj?.expectSum) < 500000)) {
                    newObj.needProofFlag = 1;
                    newObj.needProofURL = resObj?.['needProofURL'];
                  }
                  // 判断有没有进口专业人员论证意见url返回 &&  当选择是进口，才能上传专业人员论证意见
                  if (resObj?.['needImportURL'] && Boolean(newObj?.importFlag)) {
                    newObj.needImportFlag = 1;
                    newObj.needImportURL = resObj?.['needImportURL'];
                  }
                  // 判断有没有单一来源论证意见url返回 && 当选择了单一来源，才能上传单一来源论证意见
                  if (resObj?.['needSingleURL'] && Boolean(newObj?.singleFlag)) {
                    newObj.needSingleFlag = 1;
                    newObj.needSingleURL = resObj?.['needSingleURL'];
                  }
                }
                return newObj;
              });

              /**
               * 数据抛出
               * */
              setDataSource(newarr);
              dispatch({
                type: IActionEnum.UPDATE_MATERIAL_LIST,
                payload: newarr,
              });
            }}
          />
        )}
      </div>

      {/* 第二部分 服务类 */}
      {isShowTable && (
        <div className={`${prefixCls}-material-table`}>
          <div className={`${prefixCls}-material-tableTitle`}>二、服务清单</div>
          <div className="list-table">
            <Table
              dataSource={dataSource?.filter((item) => item?.supplyType == FWL_SUPPLY()) || []}
              scroll={{ x: 'true', y: 'true' }}
              rowSelection={rowSelectionMemo as any}
              pagination={false}
              size={'small'}
              columns={getNeedTableColumns({
                needInfo,
                tableForm,
                nodesFlowListMemo,
                isView,
                isEngIneer: true,
                curRes,
                onEditTable,
                setIsShowDetail: (id: string) => openDrawer({ id: id, isShow: true }),
                onProjectChange,
                openMateridal: openAddEngIneer,
                onRemove: (record: Record<string, any>) => {
                  setRemoveMaterialInfo({
                    id: record.id,
                    fullName: record.fullName,
                    isShow: true,
                  });
                },
              })}
              bordered
              rowKey={'materialIDS'}
              footer={() => BottomTableFooterRender()}
            />
          </div>
        </div>
      )}

      {/* 第三部分 工程类 */}
      {isShowTable && (
        <div className={`${prefixCls}-material-table`}>
          <div className={`${prefixCls}-material-tableTitle`}>三、工程清单</div>
          <div className="list-table">
            <Table
              dataSource={dataSource?.filter((item) => item?.supplyType == GCL_SUPPLY()) || []}
              scroll={{ x: 'true', y: 'true' }}
              rowSelection={rowSelectionMemo as any}
              pagination={false}
              size={'small'}
              columns={getNeedTableColumns({
                needInfo,
                tableForm,
                nodesFlowListMemo,
                isView,
                isEngIneer: true,
                curRes,
                onEditTable,
                setIsShowDetail: (id: string) => openDrawer({ id: id, isShow: true }),
                onProjectChange,
                openMateridal: openAddEngIneer,
                onRemove: (record: Record<string, any>) => {
                  setRemoveMaterialInfo({
                    id: record.id,
                    fullName: record.fullName,
                    isShow: true,
                  });
                },
              })}
              bordered
              rowKey={'materialIDS'}
              footer={() => BottomTableFooterRender()}
            />
          </div>
        </div>
      )}

      {/* 资金来源弹窗 */}
      {isShowProject?.isShow && (
        <SelectProjectModal
          onClose={() => setIsShowProject({})}
          onSave={(res) => onEditTable({ value: res, type: 'project', key: '', record: isShowProject?.record })}
        />
      )}
    </div>
  );
};
export default UpdateNeedMaterial;
